const _ = require('lodash');
const { Transform } = require('stream');

module.exports = async function ({ user, password, connectString, table, sql, count = 1 }) {
  const oracledb = require('oracledb');
  let metadatas;
  const stream = new Transform({ objectMode: true });
  const db = await oracledb.getConnection({ user, password, connectString });
  const st = db.queryStream(sql || `select * from ${table} where rownum<=${count}`);
  st.on("metadata", (metaData) => {
    metadatas = metaData.map(o => o.name);
  });
  st.on("data", (row) => {
    stream.push(_.zipObject(metadatas, row));
  });
  st.on("end", () => {
    stream.push(null);
    db.close();
  });
  return stream;
};
